﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using webapp4U.BOL;


namespace webapp4U.UI
{
    public partial class WebMaster_Default : System.Web.UI.Page
    {
        int CateID = -1;
        protected void Page_Load(object sender, EventArgs e)
        {
            //phan them danh muc
            btDelete.OnClientClick = "if (confirm('" + ResourceManager.GetString("DeleteConfirm") + "') == false) return false;";

            CateID = Convert.ToInt32(Request.QueryString["CateID"]);

            if (CateID == 1)
                Response.Redirect(Globals.ApplicationPath + "WebMaster/Pruducts/Category.aspx");

            if (Request.QueryString["Action"] == "Edit")
            {
                btDelete.Visible = true;
                btSave.CommandArgument = "Edit";
                btSave.Text = ResourceManager.GetString("Update");
                if (!IsPostBack)
                    Load_GetCategoryByCateID(CateID);
            }
            else
            {
                btDelete.Visible = false;
                btSave.Text = ResourceManager.GetString("AddNew");
            }

            this.Load_TreeviewCategory();

            this.XulyNoot(CateID.ToString());
        }

        // xu ly de nodes duoc bung ra
        protected void XulyNoot(string NootValue)
        {
            TreeNode n = findNode(NootValue, TreeCategory.Nodes);
            //LabelCurrentCategory.Text = n.Text; // page title
            while (n != null)
            {
                n.Expand();
                n = n.Parent;
            }
        }


        //phan them danh muc
        protected void Load_GetCategoryByCateID(int CateID)
        {
            webapp4U.BOL.Category c;
            c = webapp4U.BOL.Category.GetCategoryByID(CateID);
            txtCateName.Text = c.CateName;
            txtCateName_en.Text = c.CateName_en;
            txtCateDesc.Text = c.CateDesc.Replace("<br>", "\n");
            txtCateOrder.Text = c.CateOrder.ToString();
            HPhotoFile.Value = c.ImageUrl; // luu lai hinh cu
            dlCategoryAddEdit.SelectedValue = c.ParentCateID.ToString();
        }

        protected string FilePhoto_Upload()
        {
            string strFileName = "";
            // kiem tra xem user co chon hinh dai dien ko
            if (PhotoFile.HasFile)
            {
                // kiem tra phan mo rong cua file co hop le hay khong
                string strExtension = System.IO.Path.GetExtension(PhotoFile.FileName).ToUpper();
                if (strExtension == ".JPG" || strExtension == ".GIF" || strExtension == ".JPEG" || strExtension == ".PNG")
                {
                    // lay ten file de khong bi trung file + phan mo rong cua file can upload
                    strFileName = Common.GetFileName() + System.IO.Path.GetExtension(PhotoFile.FileName);

                    //duong dan tao save file Large
                    string strFilePathLarge = Request.PhysicalApplicationPath + "/UserUpload/Items/" + strFileName;

                    //thuc hien save file Large len server
                    EnumUpload uploadLarge = FileProcess.UpLoadImage(PhotoFile, strFilePathLarge, 200);
                }
                else
                {
                    lblMsg.Text = "File bạn chọn upload không hợp lệ.";
                    strFileName = "";
                }
            }

            return strFileName;
        }


        protected void btSave_Click(object sender, EventArgs e)
        {
            webapp4U.BOL.Category cate = new webapp4U.BOL.Category();
            cate.CateID = CateID;
            cate.AppKey = "";
            if (PhotoFile.HasFile)
                cate.ImageUrl = FilePhoto_Upload();
            else
                cate.ImageUrl = HPhotoFile.Value;
            cate.CateDesc = txtCateDesc.Text.Replace(Environment.NewLine, "<br>");
            cate.CateName = txtCateName.Text;
            cate.CateName_en = txtCateName_en.Text;
            cate.CateOrder = Convert.ToInt32(txtCateOrder.Text);
            if (dlCategoryAddEdit.SelectedItem.Value.ToString() != "")
                cate.ParentCateID = Convert.ToInt32(dlCategoryAddEdit.SelectedItem.Value);
            else
                cate.ParentCateID = 0;

            if (btSave.CommandArgument == "Edit")
            {
                // no khong the tham chieu den chinh no
                if (CateID == Globals.ConvertToInt32(dlCategoryAddEdit.SelectedItem.Value))
                    Response.Redirect(Globals.ApplicationPath + "WebMaster/Products/Category.aspx?CateID=" + CateID);
                else
                    webapp4U.BOL.Category.Update(cate);
            }
            else
            {
                webapp4U.BOL.Category.Insert(cate);

            }

            Response.Redirect(Globals.ApplicationPath + "WebMaster/Products/Category.aspx?CateID=" + CateID);

        }


        protected void btDelete_Click(object sender, EventArgs e)
        {
            bool value = webapp4U.BOL.Category.Delete(CateID);
            if (value == false)
                Response.Write("<script> alert('Bạn không được phép xóa Record này.') </script>");
            else
                Response.Redirect(Globals.ApplicationPath + "WebMaster/Products/Category.aspx");
        }


        protected void btCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Globals.ApplicationPath + "WebMaster/Products/Category.aspx");
        }



        /// <summary>
        /// /////////////////////////////////////////////////
        /// </summary>
        protected void Load_TreeviewCategory()
        {
            // phan load danh muc vao treeview
            if (!IsPostBack)
            {
                // populate the TreeView from scratch
                TreeCategory.Nodes.Clear();
                List<webapp4U.BOL.Category> rootCategory = webapp4U.BOL.Category.GetCategoryByParentCateID(Convert.ToInt32(eCategory.DanhMucSanPham)); // get root level ones
                foreach (webapp4U.BOL.Category c in rootCategory)
                {
                    TreeNode newNode;
                    newNode = new TreeNode((Globals.LangVietNam()) ? c.CateName : c.CateName_en, c.CateID.ToString());
                    //newNode.SelectAction = TreeNodeSelectAction.Expand;
                    newNode.NavigateUrl = Globals.ApplicationPath + "WebMaster/Products/Category.aspx?Action=Edit&Page=Category&CateID=" + c.CateID;
                    TreeCategory.Nodes.Add(newNode);
                    populateCategoryNode(newNode);
                }
            }
        }


        private void populateCategoryNode(TreeNode n)
        {
            List<webapp4U.BOL.Category> ChildMenu = webapp4U.BOL.Category.GetCategoryByParentCateID(Convert.ToInt32(n.Value));

            if (ChildMenu.Count == 0) // base case: leaf category 
            {
                return;
            }
            else //  recursive case : expand to show sub-categories
            {
                foreach (webapp4U.BOL.Category c in ChildMenu)
                {
                    TreeNode newNode;
                    newNode = new TreeNode((Globals.LangVietNam()) ? c.CateName : c.CateName_en, c.CateID.ToString());
                    newNode.Collapse();
                    newNode.ToolTip = c.CateID.ToString();
                    //newNode.SelectAction = TreeNodeSelectAction.Expand;
                    newNode.NavigateUrl = Globals.ApplicationPath + "WebMaster/Products/Category.aspx?Action=Edit&Page=Category&CateID=" + c.CateID;
                    n.ChildNodes.Add(newNode);
                    populateCategoryNode(newNode);
                }
            }
        }


        ///<summary>
        /// Using DFS: find node in the collection 'nodes' that matches the 'value'
        ///</summary>
        private TreeNode findNode(string value, TreeNodeCollection nodes)
        {
            foreach (TreeNode n in nodes)
            {
                if (n.Value == value)
                {
                    return n;
                }
                else // search n's child nodes
                {
                    TreeNode nChild = findNode(value, n.ChildNodes);
                    if (nChild != null)
                        return nChild;
                }
            }
            return null;
        }
    }
}